package com.gimi.cloud.jimi.gateway.service.impl;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.jwt.Jwt;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.gateway.service.CheckTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CheckTokenServiceImpl implements CheckTokenService {
    private final IRedisService redisService;
    private final SysConfigDao configDao;
    private static Logger logger = LoggerFactory.getLogger(CheckTokenServiceImpl.class);

    @Autowired
    public CheckTokenServiceImpl(IRedisService redisService, SysConfigDao configDao) {
        this.redisService = redisService;
        this.configDao = configDao;
    }

    @Override
    public ResponseCodeEnum checkToken(String token,String serviceType) {
        logger.info("进入token验证");
        String configKey = "app_jwt_token_secret";
        switch (serviceType){
            case "manage":configKey = "manage_jwt_token_secret";break;
            case "merchant":configKey = "manage_jwt_token_secret";break;
            case "app":configKey = "app_jwt_token_secret";break;
            default:break;
        }
        String redisKey = RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + configKey;
        ResponseCodeEnum code = null;
        String secret = redisService.get(redisKey);
        if(StringUtil.isBlank(secret)){
            secret = configDao.getConfigByKey(configKey);
            if(!StringUtil.isBlank(secret)){
                logger.info("===>从mysql获取token secret:" + secret);
                redisService.set(redisKey,secret);
            }
        }else{
            logger.info("===>从redis获取token secret:" + secret);
        }
        if(StringUtil.isBlank(secret)){
            logger.error("===>获取token secret失败，将使用公用secret解密");
        }

        Map<String, Object> resultMap = Jwt.validToken(token,secret);
        String state = resultMap.get("state") != null ? resultMap.get("state").toString() : "";
        switch (state){
            case "VALID":
                logger.info("===>令牌校验通过");
                break;
            case "INVALID":
                code = ResponseCodeEnum.SIGNATURE_ERROR;
                logger.error("===>非法的令牌，令牌校验未通过");
                break;
            case "EXPIRED":
                code = ResponseCodeEnum.SIGNATURE_TIMEOUT;
                logger.info("===>过期的令牌，令牌校验未通过");
                break;
            default:
                code = ResponseCodeEnum.SIGNATURE_ERROR;
                logger.error("===>令牌校验失败，校验未通过");
                break;
        }
        logger.info("token验证结束.");
        return code;
    }

}
